package com.bdqn.oa.dao.impl;

import com.bdqn.oa.dao.VoteDao;
import com.bdqn.oa.entity.Vote;
import com.bdqn.oa.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author qiaolu
 * @date 2022/7/20 17:13
 */
public class VoteDaolmpl implements VoteDao {
    private QueryRunner queryRunner= new QueryRunner();
    /**
     * 通过Voteid查询
     *
     * @param VoteId
     * @return
     * @throws SQLException
     */
    @Override
    public Vote getbyidVote(Integer VoteId) throws SQLException {
        Vote vote = null;
        try {
            String sql = "select * from vote where id = ?";
            vote = queryRunner.query(DruidUtils.getConnection(),sql,new BeanHandler<Vote>(Vote.class),VoteId);
        }catch (Exception e){
            e.printStackTrace();
        }

        return vote;
    }

    /**
     * 查询全部投票项目
     *
     * @return
     * @throws SQLException
     */
    @Override
    public List<Vote> listAllVote() throws SQLException {
        List<Vote> VoteList = null;
        try {
            String sql = "select * from vote";
            VoteList = queryRunner.query(DruidUtils.getConnection(),sql,new BeanListHandler<Vote>(Vote.class));
        }catch (Exception e){
            e.printStackTrace();
        }
        return VoteList;
    }

    /**
     * 通过匿名和不匿名查询
     *
     * @param number
     * @return
     * @throws SQLException
     */
    @Override
    public List<Vote> listbyAnonymous(Integer number) throws SQLException {
        List<Vote> VoteList = null;
        try {
            String sql = "select * from vote where anonymous=?";
            VoteList = queryRunner.query(DruidUtils.getConnection(),sql,new BeanListHandler<Vote>(Vote.class),number);
        }catch (Exception e){
            e.printStackTrace();
        }
        return VoteList;
    }

    /**
     * 添加选项投票
     *
     * @param vote
     * @return
     * @throws SQLException
     */
    @Override
    public int saveVote(Vote vote) throws SQLException {
        String sql = "insert into vote(title,description,multi,anonymous,create_by,start_time,end_time)values(?,?,?,?,?,?,?)";
        return queryRunner.update(DruidUtils.getConnection(),sql,vote.getTitle(),vote.getDescription(),vote.getMulti()
        ,vote.getAnonymous(),vote.getCreateBy(),vote.getStartTime(),vote.getEndTime());
    }

    /**
     * 修改投票选项
     *
     * @param vote
     * @return
     * @throws SQLException
     */
    @Override
    public int updateVote(Vote vote) throws SQLException {
        String sql ="update vote set title=?,description=?,multi=?,anonymous=?,create_by=? where id= ?";
        return queryRunner.update(DruidUtils.getConnection(),sql,vote.getTitle(),vote.getDescription(),vote.getMulti()
        ,vote.getAnonymous(),vote.getCreateBy(),vote.getId());
    }
}
